package com.jiujichaoshi.oauth.server.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

/**
 * Description: ContextAware工具类，用于从Spring容器中获取类对应的对象
 *
 * @author YangLong [410357434@163.com]
 * @version V1.0
 * @date 2021/2/23
 */
@Slf4j
@Component
public class CustomContextAware implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException {
        log.info("inject ApplicationContext to OnsContextAware!");
        CustomContextAware.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过类名获取对象
     *
     * @param name 类名称
     * @return 类在容器中对象
     */
    public Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过类获取此类在容器中的对象
     *
     * @param clazz 类名
     * @param <T>   泛型类
     * @return 类型对象
     */
    public <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过对象name,以及Clazz返回容器中指定的Bean
     *
     * @param name  对象名
     * @param clazz 类型
     */
    public <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}
